package lwk.thread.syn;

/**
 * @author:lwk
 * @create: 2022-08-03 19:37
 * @Description: 线程不安全的银行取钱
 */
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "结婚基金");

        Drawing zhangFu = new Drawing(account, 50, "丈夫");
        Drawing qiZi = new Drawing(account, 100, "妻子");

        zhangFu.start();
        qiZi.start();

    }
}

// 账户
class Account {
    // 余额
    int money;
    // 账户
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

// 银行：模拟取款
class Drawing extends Thread{
    // 账户
    Account account;
    // 取多少钱
    int drawingMoney;
    // 现在手上有多少钱
    int nowMoney;

    public Drawing (Account account,int drawingMoney,String name){
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
        //this.nowMoney = nowMoney;
    }

    @Override
    public void run() {
        // 判断有没有钱
        if (account.money-drawingMoney<0) {
            System.out.println(Thread.currentThread().getName()+"余额不足");
            return;
        }

        //sleep放大问题发生可能性
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 卡里余额 = 卡里余额 - 你取的钱
        account.money = account.money - drawingMoney;

        // 现在手上有多少钱 = 现在手上有多少钱 + 你取的钱
        nowMoney = nowMoney + drawingMoney;

        System.out.println(account.name+"余额为："+account.money);

        System.out.println(Thread.currentThread().getName()+"手里的钱："+nowMoney);

    }

}